package com.arvato.minipro.controller;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.net.InetAddress;
import java.net.UnknownHostException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;


public class BaseController {
	/**
	 * 设置字符集
	 * @param resp
	 */
	protected void setCharSet(HttpServletResponse resp)
	{
		resp.setContentType("text/html;charset=UTF-8");
		resp.setCharacterEncoding("utf-8");
	}
	
	/**
	 * 将vo的值 复制到do上
	 * @param fileVo
	 * @param fileDo
	 * @throws IllegalAccessException 
	 * @throws IllegalArgumentException 
	 */
	protected void copy(Object voObj, Object doObj) throws IllegalArgumentException, IllegalAccessException {
		Field[] voFields = voObj.getClass().getDeclaredFields();
		Field[] doFields = doObj.getClass().getDeclaredFields();
		for(Field voField : voFields)
		{
			voField.setAccessible(true);
			for(Field doField : doFields){
				doField.setAccessible(true);
				if(doField.getName().equals(voField.getName()) && voField.get(voObj) != null){
					doField.set(doObj, voField.get(voObj));
				}
			}
		}
	}
	
	/**
	 * Spring下载文件公用
	 * @param fileFullPath ：服务器上的文件路径
	 * @param fileName ：返给客户端的文件名称
	 * @return 
	 * @throws IOException 
	 */
	public ResponseEntity<byte[]> download(String fileFullPath, String fileName) throws IOException {
		File file = new File(fileFullPath);
		HttpHeaders headers = new HttpHeaders();
		fileName = new String((fileName).getBytes("UTF-8"), "iso-8859-1");
		// 为了解决中文名称乱码问题
		headers.setContentDispositionFormData("attachment", fileName);
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.OK);
	}
	
	/**
	 * 读取请求数据流的内容
	 * @param req
	 * @param query
	 * @return
	 * @throws IOException 
	 */
	public String getRequestStr(HttpServletRequest req){
		StringBuilder str = new StringBuilder();
		try {
			BufferedReader reader = req.getReader();
			char[]buff = new char[1024];
	        int len;
			while((len = reader.read(buff)) != -1){
			     str.append(buff,0, len);
			}
		} catch (IOException e1) {
			e1.printStackTrace();
		}
        String paramStr = str.toString();
        return paramStr;
	}
	/**
	 * 得到当前运行的主机地址和端口号
	 * @param req
	 * @return
	 */
	protected String getAddr(HttpServletRequest req) {
		// getLocalAddr
		String address = "http://" + req.getServerName() + ":" + req.getLocalPort(); 
		return address;
	}

	/**
	 * 获取远程请求的IP
	 * @param request
	 * @return
	 */
	public String getIpAddr(HttpServletRequest request){  
        String ipAddress = request.getHeader("x-forwarded-for");  
            if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {  
                ipAddress = request.getHeader("Proxy-Client-IP");  
            }  
            if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {  
                ipAddress = request.getHeader("WL-Proxy-Client-IP");  
            }  
            if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {  
                ipAddress = request.getRemoteAddr();  
                if(ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")){  
                    //根据网卡取本机配置的IP  
                    InetAddress inet=null;  
                    try {  
                        inet = InetAddress.getLocalHost();  
                    } catch (UnknownHostException e) {  
                        e.printStackTrace();  
                    }  
                    ipAddress= inet.getHostAddress();  
                }  
            }  
            //对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割  
            if(ipAddress!=null && ipAddress.length()>15){ //"***.***.***.***".length() = 15  
                if(ipAddress.indexOf(",")>0){  
                    ipAddress = ipAddress.substring(0,ipAddress.indexOf(","));  
                }  
            }  
            return ipAddress;   
    }
}
